'use strict'

import { app, protocol, BrowserWindow, ipcMain, Tray, Menu, nativeImage } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'
// nodejs的path对象
const path = require('path')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
// 定义全局系统图标变量
let tray

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1380,
    height: 830,
    // 隐藏主菜单
    autoHideMenuBar: true,
    center: true,
    // 使窗口透明
    // transparent: true,
    frame: false,
    resizable: true,
    fullscreenable: true,
    // backgroundColor: '#00000000',
    icon: path.join(__dirname, '../public/logo.ico'),
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }

  win.on('closed', () => {
    win = null
  })
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 系统托盘单击次数
let trayTimeCount = 0

/**
 * 创建系统托盘
 */
function createTray () {
  tray = new Tray(nativeImage.createEmpty())
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '播放控制',
      submenu: [
        {
          label: '播放/暂停',
          click: function () {
            win.webContents.send('audioHandler', 'play')
          }
        },
        {
          label: '上一曲',
          click: function () {
            win.webContents.send('audioHandler', 'prev')
          }
        },
        {
          label: '下一曲',
          click: function () {
            win.webContents.send('audioHandler', 'next')
          }
        }
      ]
    },
    {
      label: '退出',
      click: function () {
        app.quit()
      }
    }
  ])
  tray.setToolTip('爱音乐，听音乐~')
  // 显示程序页面
  tray.on('click', () => {
    setTimeout(() => {
      if (trayTimeCount === 0) {
        if (win.isVisible()) {
          win.hide()
        } else {
          win.show()
        }
      }
      trayTimeCount = 0
    }, 300)
  })
  tray.setContextMenu(contextMenu)
  // 双击播放/暂停
  tray.on('double-click', () => {
    win.webContents.send('audioHandler', 'play')
    trayTimeCount = 1
  })
  // 设置托盘图标
  if (process.platform === 'linux') {
    tray.setImage(path.join(__dirname, '../public/logo.png'))
  } else if (isDevelopment) {
    tray.setImage(path.join(__dirname, '../public/logo.ico'))
  } else {
    tray.setImage(path.join(path.dirname(app.getPath('exe')), '/resources/public/logo.ico'))
  }
}

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs

// 解决Linux下背景无法透明问题
if (process.platform === 'linux') {
  app.commandLine.appendSwitch('enable-transparent-visuals')
  app.disableHardwareAcceleration()
}
// 解决10.X版本跨域不成功问题(上线删除)
app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors')

app.on('ready', () => {
  setTimeout(() => {
    createWindow()
  }, 200)
  setTimeout(() => {
    createTray()
  }, 300)
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

ipcMain.on('closeMainWindow', () => win.close())
ipcMain.on('minimizeMainWindow', () => win.minimize())
ipcMain.on('turnOnDevTool', () => win.webContents.openDevTools())
// 接收最小化命令
ipcMain.on('window-min', () => win.minimize())
// 接收最大化命令
ipcMain.on('window-max', () => {
  if (win.isMaximized()) {
      win.restore()
  } else {
    win.maximize()
  }
})
ipcMain.on('show-window', () => win.maximize())
ipcMain.on('orignal-window', () => win.restore())
// 设置托盘的提升语
ipcMain.on('tray-setToolTip', (event, arg) => {
  tray.setToolTip(arg)
})
